<?php

namespace App\Api\Controllers\CustomerApplets;

use Illuminate\Http\Request;
use App\Api\Controllers\CustomerApplets\BaseController;
use App\Models\CustomerAppletsUser;
use App\Models\MerchantStoreAppidSecret;
use App\Models\CustomerAppletsUserWechat;
use App\Models\CustomerAppletsUserAlipay;
use Illuminate\Support\Facades\DB;

use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;

class UserController extends BaseController
{
    /**
     * 用户从小程序端授权登录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function userLogin(Request $request){
        $requestAllData = $request->all();

        if(!isset($requestAllData['store_id']) || empty($requestAllData['store_id'])){
            return $this->responseDataJson(4002);
        }

        if(!isset($requestAllData['terminal_type']) || empty($requestAllData['terminal_type'])){
            return $this->responseDataJson(4003);
        }

        $merchantStoreAppIdSecretModel  = new MerchantStoreAppidSecret();
        //查询门店的配置信息
        $merchantStoreAppIdSecretResult = $merchantStoreAppIdSecretModel->getStoreAppIdSecret($requestAllData['store_id']);
        switch ($requestAllData['terminal_type']){
            //微信授权登录
            case config("api.weChat"):
                if(!isset($requestAllData['code']) || empty($requestAllData['code'])){
                    return $this->responseDataJson(4008);
                }
                if(empty($merchantStoreAppIdSecretResult->wechat_appid)){
                    return $this->responseDataJson(4004);
                }
                // if(empty($merchantStoreAppIdSecretResult->wechat_secret)){
                //     return $this->responseDataJson(4005);
                // }

                // $userWeChatInfo = $this->getWeChatOpenId($requestAllData['code'],$merchantStoreAppIdSecretResult->wechat_appid,$merchantStoreAppIdSecretResult->wechat_secret);
                $userWeChatInfo = $this->getWeChatOpenId($requestAllData['code'],$merchantStoreAppIdSecretResult->wechat_appid);
                $userWeChatResult = json_decode($userWeChatInfo,true);

                if(isset($userWeChatResult['openid']) && !empty($userWeChatResult['openid'])){

                    //按照openid查询，之前是否已经授权
                    $customerAppletsUserWeChatModel = new CustomerAppletsUserWechat();

                    $userWeChatInfoResult = $customerAppletsUserWeChatModel->getUserOpenidInfo($requestAllData['store_id'],$userWeChatResult['openid'],$requestAllData['code'],$userWeChatResult['session_key']);

                    if(!$userWeChatInfoResult){
                        return $this->responseDataJson(202,"查询用户openid失败");
                    }
                    if(isset($userWeChatInfoResult['status']) && !empty($userWeChatInfoResult['status']) && $userWeChatInfoResult['status'] == 202){
                        return $this->responseDataJson(202,$userWeChatInfoResult['message']);
                    }
                    return $this->responseDataJson(200,"",["openid" => $userWeChatResult['openid'],"session_key" => $userWeChatResult['session_key'],'user_id' => $userWeChatInfoResult]);
                }else{
                    return $this->responseDataJson(202,$userWeChatResult['errmsg']);
                }

                break;
            //支付宝授权登录
            case config("api.aliPay"):
                if(!isset($requestAllData['code']) || empty($requestAllData['code'])){
                    return $this->responseDataJson(4009);
                }
                if(empty($merchantStoreAppIdSecretResult->alipay_appid)){
                    return $this->responseDataJson(4006);
                }

                $userAliPayInfo = $this->getAliPayOauthToken($requestAllData['code'],$merchantStoreAppIdSecretResult->alipay_appid,$merchantStoreAppIdSecretResult->alipay_rsaPrivateKey,$merchantStoreAppIdSecretResult->alipay_alipayrsaPublicKey);

                if($userAliPayInfo['status'] == 200){

                    //按照openid查询，之前是否已经授权
                    $customerAppletsUserAliPayModel = new CustomerAppletsUserAlipay();

                    $userAliPayResult = $customerAppletsUserAliPayModel->getUserAliPayUserIdInfo($requestAllData['store_id'],$userAliPayInfo['user_id'],$requestAllData['code']);

                    if(!$userAliPayResult){
                        return $this->responseDataJson(202);
                    }
                    if(isset($userAliPayResult['status']) && !empty($userAliPayResult['status']) && $userAliPayResult['status'] == 202){
                        return $this->responseDataJson(202,$userAliPayInfo['message']);
                    }
                    return $this->responseDataJson(200,"",['access_token' => $userAliPayInfo['access_token'] , 'user_id' => $userAliPayResult,'ali_user_id' => $userAliPayInfo['user_id']]);

                }else{
                    return $this->responseDataJson(202,$userAliPayInfo['errmsg']);
                }
                break;
        }
    }

    /**
     * 更新用户信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function updateUserInfo(Request $request){
        $requestAllData = $request->all();

        if(!isset($requestAllData['user_id']) || empty($requestAllData['user_id'])){
            return $this->responseDataJson(4001);
        }

        if(!isset($requestAllData['store_id']) || empty($requestAllData['store_id'])){
            return $this->responseDataJson(4002);
        }

        if(!isset($requestAllData['terminal_type']) || empty($requestAllData['terminal_type'])) {
            return $this->responseDataJson(4003);
        }

        //创建本系统平台的token（用户请求接口的凭证）
        $customerAppletsUserModel  = new CustomerAppletsUser();
        $customerAppletsUserStoreResult = $customerAppletsUserModel->getUserInfo($requestAllData['user_id'],$requestAllData['store_id']);

        $token = JWTAuth::fromUser($customerAppletsUserStoreResult);//根据用户得到token

        switch ($requestAllData['terminal_type']){
            //微信数据
            case config("api.weChat"):

                $customerAppletsUserWeChatModel = new CustomerAppletsUserWechat();

                $userWeChatInfoResult = $customerAppletsUserWeChatModel->updateUserWeChatInfo($requestAllData['user_id'],$requestAllData['store_id'],$requestAllData);

                if(!$userWeChatInfoResult){
                    return $this->responseDataJson(202);
                }
                if(isset($userAliPayResult['status']) && !empty($userAliPayResult['status']) && $userAliPayResult['status'] == 202){
                    return $this->responseDataJson(202,$userWeChatInfoResult['message']);
                }

                return $this->responseDataJson(200,"数据更新成功",['user_id' => $requestAllData['user_id'],'token' => $token]);
                break;
            //支付宝数据
            case config("api.aliPay"):
                $customerAppletsUserAliPayModel = new CustomerAppletsUserAlipay();

                $userWeChatInfoResult = $customerAppletsUserAliPayModel->updateUserAliPayInfo($requestAllData['user_id'],$requestAllData['store_id'],$requestAllData);

                if(isset($userAliPayResult['status']) && !empty($userAliPayResult['status']) && $userAliPayResult['status'] == 202){
                    return $this->responseDataJson(202,$userWeChatInfoResult['message']);
                }
                return $this->responseDataJson(200,"数据更新成功",['user_id' => $requestAllData['user_id'],'token' => $token]);
                break;
        }

    }

    /**
     * 请求微信接口获取用户手机号
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserMobile(Request $request){
        $requestAllData = $request->all();

        if(!isset($requestAllData['user_id']) || empty($requestAllData['user_id'])){
            return $this->responseDataJson(4001);
        }

        if(!isset($requestAllData['store_id']) || empty($requestAllData['store_id'])){
            return $this->responseDataJson(4002);
        }

        if(!isset($requestAllData['terminal_type']) || empty($requestAllData['terminal_type'])) {
            return $this->responseDataJson(4003);
        }

        switch ($requestAllData['terminal_type']) {
            //微信接口获取手机号
            case config("api.weChat"):

                if(!isset($requestAllData['iv']) || empty($requestAllData['iv'])) {
                    return $this->responseDataJson(202,"iv参数不可为空");
                }

                if(!isset($requestAllData['session_key']) || empty($requestAllData['session_key'])) {
                    return $this->responseDataJson(202,"session_key参数不可为空");
                }

                if(!isset($requestAllData['encryptedData']) || empty($requestAllData['encryptedData'])) {
                    return $this->responseDataJson(202,"encryptedData参数不可为空");
                }

                $customerAppletsUserModel  = new CustomerAppletsUser();
                $customerAppletsUserStoreResult = $customerAppletsUserModel->getUserMobile($requestAllData['user_id'],$requestAllData['store_id'],$requestAllData['session_key'],$requestAllData['encryptedData'],$requestAllData['iv']);

                if(!$customerAppletsUserStoreResult){
                    return $this->responseDataJson(202);
                }
                if(isset($userAliPayResult['status']) && !empty($userAliPayResult['status']) && $userAliPayResult['status'] == 202){
                    return $this->responseDataJson(202,$customerAppletsUserStoreResult['message']);
                }

                return $this->responseDataJson(200,"数据获取成功",['mobile' => $customerAppletsUserStoreResult['message']]);

                break;
            //支付宝数据
            case config("api.aliPay"):
                $merchantStoreAppIdSecretModel  = new MerchantStoreAppidSecret();
                //查询门店的配置信息
                $merchantStoreAppIdSecretResult = $merchantStoreAppIdSecretModel->getStoreAppIdSecret($requestAllData['store_id']);
                if(!$merchantStoreAppIdSecretResult->alipay_appid){
                    return $this->responseDataJson(202,"该商家支付宝小程序未授权","");
                }
                //如果是用户手动输入的话，不需要进行与支付宝平台进行对接
                if(isset($requestAllData['mobile']) && !empty($requestAllData['mobile'])){
                    $aliPayUserMobileResult = ['code' => '10000','mobile' => $requestAllData['mobile']];
                }else{
                    $result = DB::table("customerapplets_authorize_appids")->select("id","t_appid","AuthorizerAppid","aliPay_aes")->where([
                        'AuthorizerAppid' => $merchantStoreAppIdSecretResult->alipay_appid,
                        'applet_type' => 2,
                    ])->first();
                    if(empty($result)){
                        return $this->responseDataJson(202,"请先授权到第三方应用","");
                    }
                    if(!$result->aliPay_aes){
                        return $this->responseDataJson(202,"请先设置aes密钥","");
                    }
                    $aliPayUserMobileResult = $this->getAliPayMobile($requestAllData['encryptedData'],$result->aliPay_aes);
                }

                if($aliPayUserMobileResult['code'] == '10000'){
                    DB::table("customerapplets_user_alipays")->where(['user_id' => $requestAllData['user_id'],'store_id' => $requestAllData['store_id']])->update([
                        'alipay_mobile' => $aliPayUserMobileResult['mobile'],
                        'updated_at'    => date("Y-m-d H:i:s",time())
                    ]);
                    return $this->responseDataJson(200,"数据获取成功",['mobile' => $aliPayUserMobileResult['mobile']]);
                }else{
                    return $this->responseDataJson(202,"数据获取失败",$aliPayUserMobileResult['msg']);
                }
                break;
        }
    }

    /**
     * 获取用户信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserWeChatOrAliPayInfo(Request $request){
        $requestAllData = $request->all();

        $customerAppletsUserModel = new CustomerAppletsUser();
        $result = $customerAppletsUserModel->getUserWeChatOrAliPayInfo($requestAllData['user_id'],$requestAllData['store_id'],$requestAllData['terminal_type']);
        if(!$result){
            return $this->responseDataJson(202);
        } else if(is_numeric($result) && $result == 405){
            return $this->responseDataJson(405);
        }else{
            return $this->responseDataJson(200,"",$result);
        }
    }
}
